document.getElementById('research-link').addEventListener('click', function () { // 假设有一个研究链接
    showContent('research-edit');

    fetch('/research/manage', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            var researchManageDiv = document.getElementById('research-manage');
            researchManageDiv.innerHTML = '<h2>研究管理界面</h2>';
            data.researches.forEach(research => {
                researchManageDiv.innerHTML += `
<table>
    <tr>
        <td>研究名称：</td>
        <td>${research.name}</td>
    </tr>
    <tr>
        <td>设备信息：</td>
        <td>${research.device_info}</td>
    </tr>
    <tr>
        <td>成就：</td>
        <td>${research.achievement}</td>
    </tr>
    <tr>
        <td>合作伙伴：</td>
        <td>${research.partner}</td>
    </tr>
</table>
<button onclick="delete_research('${research.id}')" class="btn btn-lg btn-primary btn-block">删除研究</button>
<button onclick="update_research('${research.id}')" class="btn btn-lg btn-primary btn-block">更新研究</button>
<br>
`;
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
});

document.getElementById('add-research').addEventListener('click', function () {
    document.getElementById('research-form').style.display = 'block'; // 显示新增研究的表单
});

document.getElementById('submit-research').addEventListener('click', function () {
    var researchData = {
        name: document.getElementById('research-name').value,
        device_info: document.getElementById('research-device_info').value,
        achievement: document.getElementById('research-achievement').value,
        partner: document.getElementById('research-partner').value
    };

    fetch('/research/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(researchData)
    })
        .then(response => response.json())
        .then(data => {
            alert('研究新增成功！');
            document.getElementById('research-form').style.display = 'none'; // 隐藏表单
            location.reload();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('新增失败，请重试！');
        });
});

function delete_research(researchId) {
    fetch('/research/delete/' + researchId + '/', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                throw new Error('删除研究失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}
